<?php
/**
 * UnWidow View Helper
 * This view helper prevents widow text. A widow is when a single word is
 * brought to the next line when you run out of space. For instance, this block
 * of text will have a widow to demonstrate a point. Here is more text for an
 * example.
 *
 * The word "example" is a widow in the previous paragraph. This helper prevents
 * widows, which are a huge no-no in the typesetting industry but are typically
 * ignored on the web. It does this by replacing the last space in the text with
 * a non-breaking space so that if there is a widow, there will be at least two
 * words on the next line rather than one.
 *
 * Passing in a second parameter will allow you to specify how many words should
 * be brought down in the case of a widow.
 *
 * @package     Visi
 * @subpackage  View Helpers
 * @author      Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright   (c) 2011 Coalition Technologies <joel@coalitiontechnologies.com>
 * @version     $Id$
 */
class Visi_View_Helper_UnWidow extends Zend_View_Helper_Abstract {

    /**
     * @note This helper automatically does escaping so do NOT escape when using
     * this helper.
     */
    public function unWidow($text, $limit = null, $escape = true) {
    
        if (is_null($limit)) $limit = 1;
        if ($escape) $text = $this->view->escape($text);
        $reverse = strrev($text);
        // replace the last space (or if more were requested, replace that last
        // "$limit" spaces with a non-breaking space
        $unwidowed = preg_replace('/ +/', ';psbn&', $reverse, $limit);
        return strrev($unwidowed);
    
    }

}